package com.demo2do.fms.admin.web.controller.supplier.management;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.search.supplier.VehicleSourceSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.service.supplier.TractorService;
import com.demo2do.fms.admin.service.supplier.TrailerService;
import com.demo2do.fms.admin.service.supplier.VehicleSourceService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.supplier.common.Supplier;
import com.demo2do.fms.entity.vehicle.AuditStatus;
import com.demo2do.fms.entity.vehicle.source.SyncStatus;
import com.demo2do.fms.entity.vehicle.source.VehicleSource;
import com.demo2do.fms.entity.vehicle.tractor.Tractor;
import com.demo2do.fms.entity.vehicle.trailer.Trailer;

/**
 * 
 * 车辆信息管理
 * 
 */
@Controller
@RequestMapping("/vehicle-sources")
@MenuSetting("menu-supplier")
public class VehicleSourceController {
    
    private static final Logger logger = LoggerFactory.getLogger(VehicleSourceController.class);
    
    @Autowired
    private VehicleSourceService vehicleSourceService;

    @Autowired
    private TractorService tractorService;
    
    @Autowired
    private TrailerService trailerService;
    
    @Autowired
    private SupplierService supplierService;
    
    /**
     * 车辆列表页
     * 
     * @param login
     * @param status
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-self-vehicle-management")
    public ModelAndView list(@Secure Login login, @RequestParam(name = "status", required = false, defaultValue = "UNSYNC") SyncStatus status,
                             HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-list");
        
        int totals = vehicleSourceService.count(login, status);
        if (totals > 0) {

            List<VehicleSource> vehicleSources = vehicleSourceService.list(login, status, page.with(totals));
            modelAndView.addObject("vehicleSources", vehicleSources);
            
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        modelAndView.addObject("supplier", login.isSupplier());
        modelAndView.addObject("status", status);
        modelAndView.addObject("vam", login.isVam());
        
        return modelAndView;
        
    }
    
    /**
     * 过滤查询panel
     * 
     * @param status
     * @param synchronize
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search(@RequestParam("status") SyncStatus status) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-search");
        
        modelAndView.addObject("status", status);
        
        return modelAndView;
        
    }
    
    /**
     * 过滤查询
     * 
     * @param login
     * @param search
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-self-vehicle-management")
    public ModelAndView onSearch(@Secure Login login, VehicleSourceSearch search,
                                 HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-list");
        
        if (login.isSupplier()) {
            search.setSupplierId(login.getSupplierId());
        }
        
        Boolean bind = search.getBind();
        if (bind != null && BooleanUtils.isTrue(bind)) {
            search.addBindDriver();
        }
        if (bind != null && BooleanUtils.isFalse(bind)) {
            search.addUnbindDriver();
        }
        
        int totals = vehicleSourceService.count(search);
        if (totals > 0) {
            
            List<VehicleSource> vehicleSources = vehicleSourceService.search(search, page.with(totals));
            modelAndView.addObject("vehicleSources", vehicleSources);
            
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
            
        }
        
        modelAndView.addObject("supplier", login.isSupplier());
        modelAndView.addObject("status", search.getStatus());
        modelAndView.addObject("vam", login.isVam());
        
        return modelAndView;
        
    }
    
    /**
     * 绑定车辆panel
     * 
     * @return
     */
    @RequestMapping(value = "/bind", method = RequestMethod.GET)
    public ModelAndView bind(@Secure Login login) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-bind");
        
        Supplier supplier = supplierService.load(Supplier.class, login.getSupplierId());
        
        // list tractor
        List<Tractor> tractors = tractorService.listUnbind(supplier, AuditStatus.QUALIFIED);
        modelAndView.addObject("tractors", tractors);
        
        // list trailer
        List<Trailer> trailers = trailerService.listUnbind(supplier, AuditStatus.QUALIFIED);
        modelAndView.addObject("trailers", trailers);
        
        return modelAndView;
        
    }
    
    /**
     * 绑定车辆
     * 
     * @param login
     * @param tractorId
     * @param trailerId
     * @return
     */
    @RequestMapping(value = "/bind", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onBind(@Secure Login login, 
                                           @RequestParam("tractorId") Long tractorId,
                                           @RequestParam(name = "trailerId", required = false) Long trailerId) {

    	HttpResult httpResult = new HttpResult();
        
        try {
            
            Tractor tractor = tractorService.load(Tractor.class, tractorId);
            
            vehicleSourceService.bind(tractor, trailerId, login);
            
            httpResult.success().message("绑定成功");
            
        } catch (Exception e) {
            logger.error("#onBind() - bind vehicle fail, exception is [{}]", e);
            httpResult.fail("500").message("绑定失败! " + e.getMessage());
        }
        
        return httpResult;
        
    }
    
    /**
     * 解绑
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/unbind", method = RequestMethod.GET)
    public ModelAndView unbind(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-unbind");
        
        modelAndView.addObject("id", id);

        return modelAndView;
    }

    /**
     * 解绑
     * 
     * @param vehicleSource
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/unbind", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onUnbind(@Preloading("id") VehicleSource vehicleSource,
                                             @Secure(property = "id") Long operator) {

        HttpResult httpResult = new HttpResult();

        try {
            
            vehicleSourceService.unbind(vehicleSource, operator);
            
            httpResult.success().message("解绑成功");
            
        } catch (Exception e) {
            httpResult.success().message("解绑失败！" + e.getMessage());
            logger.error("#onUnbind - unbind vehicle source fail, exception = [{}]", e);
        }

        return httpResult;
    }
    
    /**
     * 换挂
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/change-trailer", method = RequestMethod.GET)
    public ModelAndView changeTrailer(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-change-trailer");
        
        // 1. load vehicle_source
        VehicleSource vehicleSource = vehicleSourceService.load(VehicleSource.class, id);
        modelAndView.addObject("vehicleSource", vehicleSource);
        
        // 2. list trailers
        List<Trailer> trailers = trailerService.list(vehicleSource.getSupplier(), AuditStatus.QUALIFIED);
        modelAndView.addObject("trailers", trailers);

        return modelAndView;
        
    }
    
    /**
     * query vehicle_source by trailer
     * 
     * @param trailerId
     * @return
     */
    @RequestMapping(value = "/query-trailer", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult queryVehicle(@RequestParam("trailerId") Long trailerId) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            VehicleSource vehicleSource = vehicleSourceService.loadVehicleSource(trailerId);
            
            httpResult.success().data("brandCNCode", vehicleSource.getTractorBrandCode())
                                .data("synchronize", vehicleSource.getSynchronize())
                                .message("查询成功");
            
        } catch (Exception e) {
            logger.error("#queryVehicle() - query fail, exception = [{}]", e);
            httpResult.fail("500").message("查询失败");
        }
        
        return httpResult;
        
    }

    /**
     * 
     * @param operator
     * @param vehicleId
     * @param trailerId
     * @param changedTrailerId
     * @return
     */
    @RequestMapping(value = "/{id}/change-trailer", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onChangeTrailer(@Secure(property = "id") Long operator,
                                                    @RequestParam("vehicleId") Long vehicleId,
                                                    @RequestParam("trailerId") Long trailerId) {

        HttpResult httpResult = new HttpResult();
        
        try {
            
            VehicleSource vehicleSource = vehicleSourceService.load(VehicleSource.class, vehicleId);
            vehicleSourceService.changeTrailer(vehicleSource, trailerId, operator);
            
            httpResult.success().message("更换挂车成功");
            
        } catch (BusinessException e) {
            logger.error("#onChangeTrailer() - change fail, business exception = [{}]", e);
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            logger.error("#onChangeTrailer() - change fail, exception = [{}]", e);
            httpResult.fail("500").message("更换挂车失败");
        }

        return httpResult;
    }

    /**
     * 引入申报panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/declare", method = RequestMethod.GET)
    public ModelAndView declare(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-declare");
        
        VehicleSource vehicleSource = vehicleSourceService.load(VehicleSource.class, id);
        
        modelAndView.addObject("vehicleSource", vehicleSource);

        return modelAndView;
        
    }

    /**
     * 引入申报
     * 
     * @param operator
     * @param vehicleSource
     * @return
     */
    @RequestMapping(value = "/{id}/declare", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onDeclare(@Preloading("id") VehicleSource vehicleSource, @Secure(property = "id") Long operator) {

        HttpResult httpResult = new HttpResult();
        
        try {
            
            vehicleSourceService.declare(vehicleSource, operator);
            
            httpResult.success().message("引入申报成功");
            
        } catch (Exception e) {
            logger.error("#onDeclare() - declare fail, exception is [{}]", e);
            httpResult.fail("500").message("引入申报失败，" + e.getMessage());
        }

        return httpResult;
        
    }

    /**
     * 取消引入申报panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/cancel-declare", method = RequestMethod.GET)
    public ModelAndView cancelDeclare(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-cancel-declare");
        
        modelAndView.addObject("id", id);

        return modelAndView;
        
    }

    /**
     * 取消引入申报
     * 
     * @param operator
     * @param vehicleSource
     * @return
     */
    @RequestMapping(value = "/{id}/cancel-declare", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onCancelDeclare(@Preloading("id") VehicleSource vehicleSource, @Secure(property = "id") Long operator) {

        HttpResult httpResult = new HttpResult();
        
        try {
            
            vehicleSourceService.cancelDeclare(vehicleSource, operator);
            
            httpResult.success().message("取消引入申报成功");
            
        } catch (Exception e) {
            logger.error("onCancelDeclare - cancel declare fail, exception is [{}]", e);
            httpResult.fail("500").message("取消引入申报失败！" + e.getMessage());
        }

        return httpResult;
        
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/out", method = RequestMethod.GET)
    public ModelAndView out(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/vehicle/vehicle-info-out");
        
        VehicleSource vehicleSource = vehicleSourceService.load(VehicleSource.class, id);
        modelAndView.addObject("vehicleSource", vehicleSource);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param vehicleSource
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/out", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onOut(@Preloading("vehicleId") VehicleSource vehicleSource,
                                          @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            vehicleSourceService.out(vehicleSource, operator);
            
            httpResult.success().message("车辆转出成功");
            
        } catch (Exception e) {
            logger.error("#onOut() - occur business exception=[{}]", e);
            httpResult.fail("500").message("车辆转出失败！" + e.getMessage());
        }
        
        return httpResult;
        
    }

}
